package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkSpaceService workSpaceService;
    /**
     * 营业额统计
     * @param  begin,  end
     *          {
     *              begin: "2023-01-01",
     *              end: "2023-01-07"
     *          }
     * @return TurnoverReportVO
     *          {
     *              dateList: "2023-01-01,2023-01-02,2023-01-03,2023-01-04,2023-01-05,2023-01-06,2023-01-07",
     *              turnoverList: "100,200,300,400,500,600,700"
     *          }
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin , LocalDate end) {
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        ArrayList<String> dateList = new ArrayList<>();
        ArrayList<String> turnoverList = new ArrayList<>();
//        //计算出间隔的每天的日期
//        turnoverReportVO.setDateList(""+begin);
//        String turnoverByDateAndStatus = reportMapper.getTurnoverByDateAndStatus(begin, Orders.COMPLETED);
//        if (turnoverByDateAndStatus == null) {
//            turnoverByDateAndStatus = "0";
//        }
//        turnoverReportVO
//                .setTurnoverList( "" +turnoverByDateAndStatus);
        for (LocalDate date = begin; !date.equals(end); date = date.plusDays(1)) {
            //计算出当天的日期(MM-dd)
            String dateStr = date.format(DateTimeFormatter.ofPattern("MM-dd"));
//            turnoverReportVO.setDateList(turnoverReportVO.getDateList() + "," + dateStr);
            dateList.add(dateStr);
            //根据日期查询当天的营业额
            //将营业额添加到turnoverList中
            String turnoverByDateAndStatus = reportMapper.getTurnoverByDateAndStatus(date, Orders.COMPLETED);
            if (turnoverByDateAndStatus == null) {
                turnoverByDateAndStatus = "0";
            }
//            turnoverReportVO
//                    .setTurnoverList(turnoverReportVO.getTurnoverList() + "," +turnoverByDateAndStatus);
            turnoverList.add(turnoverByDateAndStatus);
        }
//        turnoverReportVO.setDateList(turnoverReportVO.getDateList() + "," + end);
        dateList.add(end.format(DateTimeFormatter.ofPattern("MM-dd")));
        String turnoverByDateAndStatus = reportMapper.getTurnoverByDateAndStatus(end, Orders.COMPLETED);
        if (turnoverByDateAndStatus == null) {
            turnoverByDateAndStatus = "0";
        }
//        turnoverReportVO
//                .setTurnoverList(turnoverReportVO.getTurnoverList() + "," +turnoverByDateAndStatus);
        turnoverList.add(turnoverByDateAndStatus);
        turnoverReportVO.setDateList(StringUtils.join(dateList,","));
        turnoverReportVO.setTurnoverList(StringUtils.join(turnoverList,","));
        return turnoverReportVO;

    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     * * {
     *    "code": 0,
     *    "data": {
     *      "dateList": "string", //日期列表
     *      "orderCountList": "string", //每日订单数
     *      "validOrderCountList": "string" // 每日有效订单数
     *      "totalOrderCount": 0, //总订单数
     *      "validOrderCount": 0, //有效订单数
     *      "orderCompletionRate": 0, // 订单完成率
     *    },
     *    "msg": "string"
     *  }
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        OrderReportVO orderReportVO = new OrderReportVO();
        ArrayList<String> dateList = new ArrayList<>();
        ArrayList<String> orderCountList = new ArrayList<>();
        ArrayList<String> validOrderCountList = new ArrayList<>();
        //日期列表
        while (!begin.equals(end)){
//            orderReportVO.setDateList(orderReportVO.getDateList()+","+begin);
            dateList.add(begin+"");
            //获得每日的开始时间
            LocalDateTime min = begin.atTime(LocalTime.MIN);
            LocalDateTime max = begin.atTime(LocalTime.MAX);
            //获得每日订单数
            Integer orderCount = ordersMapper.countByTimeAndStatus(null, min, max);
//            orderReportVO.setOrderCountList(orderReportVO.getOrderCountList()+","+orderCount);
            orderCountList.add(orderCount.toString());
            //获得每日有效订单数
            Integer validOrderCount = ordersMapper.countByTimeAndStatus(Orders.COMPLETED, min, max);
//            orderReportVO.setValidOrderCountList(orderReportVO.getValidOrderCountList()+","+validOrderCount);
            validOrderCountList.add(validOrderCount.toString());
            begin = begin.plusDays(1);
        }
//        orderReportVO.setDateList(orderReportVO.getDateList()+","+end);
        dateList.add(end+"");
        //获得最后一日的开始时间
        LocalDateTime min = end.atTime(LocalTime.MIN);
        LocalDateTime max = end.atTime(LocalTime.MAX);
        //获得最后一日订单数
        Integer orderCountEnd = ordersMapper.countByTimeAndStatus(null, min, max);
//        orderReportVO.setOrderCountList(orderReportVO.getOrderCountList()+","+orderCountEnd);
        orderCountList.add(orderCountEnd.toString());
        //获得最后一日有效订单数
        Integer validOrderCountEnd = ordersMapper.countByTimeAndStatus(Orders.COMPLETED, min, max);
//        orderReportVO.setValidOrderCountList(orderReportVO.getValidOrderCountList()+","+validOrderCountEnd);
        validOrderCountList.add(validOrderCountEnd.toString());
        //获取总订单数
        Integer orderCount = ordersMapper.countByTimeAndStatus(null, null, null);
        orderReportVO.setTotalOrderCount(orderCount);
        //获取有效订单数
        Integer validOrderCount = ordersMapper.countByTimeAndStatus(Orders.COMPLETED, null, null);
        orderReportVO.setValidOrderCount(validOrderCount);
        //订单完成率
        orderReportVO.setOrderCompletionRate((double) validOrderCount / orderCount);
        //存入VO
        orderReportVO.setDateList(StringUtils.join(dateList,","));
        orderReportVO.setOrderCountList(StringUtils.join(orderCountList,","));
        orderReportVO.setValidOrderCountList(StringUtils.join(validOrderCountList,","));
        return orderReportVO;
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     * {
     *   "code": 0,
     *   "data": {
     *     "dateList": "string", // 日期列表
     *     "newUserList": "string", // 新增用户列表
     *     "totalUserList": "string" // 总用户列表
     *   },
     *   "msg": "string"
     * }
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        UserReportVO userReportVO = new UserReportVO();
        //日期列表
        ArrayList<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        //新增用户列表
        ArrayList<String> newUserList = new ArrayList<>();
        //总用户列表
        ArrayList<String> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //获得每日的开始时间
            LocalDateTime min = date.atTime(LocalTime.MIN);
            LocalDateTime max = date.atTime(LocalTime.MAX);
            //获得每日新增用户数
            Integer newUserCount = userMapper.countByCreateTime(min, max);
            newUserList.add(newUserCount.toString());
            //获得每日总用户数
            Integer totalUserCount = userMapper.countByCreateTime(null, max);
            totalUserList.add(totalUserCount.toString());
        }
        userReportVO.setDateList(StringUtils.join(dateList,","));
        userReportVO.setNewUserList(StringUtils.join(newUserList,","));
        userReportVO.setTotalUserList(StringUtils.join(totalUserList,","));
        return userReportVO;
    }

    /**
     * 销售top10
     * @param begin
     * @param end
     * @return
     * {
     *   "code": 0,
     *   "data": {
     *     "nameList": "string", // 商品名称列表
     *     "numberList": "string" // 销售数量列表
     *   },
     *   "msg": "string"
     * }
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        ArrayList nameList = new ArrayList();
        ArrayList numberList = new ArrayList();
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //根据时间选择区间，展示销量前10的菜品名称
        List<GoodsSalesDTO> list = ordersMapper.getSalesTop10(beginTime, endTime);
        //遍历list，将名称拼接成字符串
        for (GoodsSalesDTO goodsSalesDTO : list) {
//            salesTop10ReportVO.setNameList(salesTop10ReportVO.getNameList()+","+goodsSalesDTO.getName());
//            salesTop10ReportVO.setNumberList(salesTop10ReportVO.getNumberList()+","+goodsSalesDTO.getNumber());
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }
        salesTop10ReportVO.setNameList(StringUtils.join(nameList,","));
        salesTop10ReportVO.setNumberList(StringUtils.join(numberList,","));
        return salesTop10ReportVO;
    }

    /**
     * 导出excel数据
     */
    @Override
    public void export(HttpServletResponse response) {
        //获取前30天的时间范围
        LocalDateTime begin = LocalDateTime.now().with(LocalTime.MIN).minusDays(30);
        LocalDateTime end = LocalDateTime.now().with(LocalTime.MAX).minusDays(1);
        //获取模板输入流
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //创建Excel文件
        try {
            XSSFWorkbook sheets = new XSSFWorkbook(in);
            //获取第一个sheet
            XSSFSheet sheet = sheets.getSheet("Sheet1");
            //获取第二行填入时间
            sheet.getRow(1).getCell(1).setCellValue("时间"+begin + "至" + end);
            //获取需要填入的数据
            BusinessDataVO businessDataVO = workSpaceService.businessData(begin, end);
            //获取第四行
            XSSFRow row = sheet.getRow(3);
            //填充营业额
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            //填充订单完成率
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //填充新增用户数
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //获取第五行
            row = sheet.getRow(4);
            //填充有效订单数
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //填冲平均单客价
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.toLocalDate().plusDays(i);
                //查询某一天的明细数据
                BusinessDataVO businessData = workSpaceService.businessData(date.atStartOfDay(), date.atTime(LocalTime.MAX));
                //获取第八行
                row = sheet.getRow(7 + i);
                //填充日期
                row.getCell(1).setCellValue(date.toString());
                //填充营业额
                row.getCell(2).setCellValue(businessData.getTurnover());
                //填充有效订单
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                //填充订单完成率
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                //填充平均单价
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                //填充新增用户数
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //输出到浏览器
            ServletOutputStream out = response.getOutputStream();
            sheets.write(out);
            //关闭流
            out.close();
            sheets.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
